package player;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import main.Game;

import org.apache.log4j.Logger;

public class PlayerManager 
{ 
	static Logger logger = Logger.getLogger(Game.class);
	
	public PlayerManager()
	{
		playerMap = new HashMap<Integer, Player>();
	}
	
	public static int generateRuntimeID()
	{
		int runtimeID = 0;
		
		synchronized(PlayerManager.class)
		{
			playerRuntimeID++;
			if (playerRuntimeID >= Integer.MAX_VALUE)
			{
				playerRuntimeID = 0;
			}
			
			runtimeID = playerRuntimeID;
		}
		
		return runtimeID;
	}
	
	public boolean addPlayer(Player player)
	{
		int    runtimeID = player.getRuntimeID();
		Player oldPlayer = null;
		  
		synchronized(playerMap)
		{
			oldPlayer = playerMap.put(runtimeID, player); 	
		}
		
		player.setPlayerManager(this);
		
		if (oldPlayer != null)
		{
			logger.error("player runtime id duplicate.");
			return false;
		}
		
		return true;
	}
	
	public boolean removePlayer(Player player)
	{
		int    runtimeID  = player.getRuntimeID();
		Player findPlayer = null;
		
		synchronized(playerMap)
		{
			findPlayer = playerMap.remove(runtimeID);
		}
		
		if (findPlayer == null)
		{
			logger.error("try remove absent player from player manager.");
			return false;
		}
		
		return true;
	}
	
	public Player getPlayer(int runtimeID)
	{
		Player player = null;
		
		synchronized(playerMap)
		{
			player = playerMap.get(runtimeID);
		}
		
		return player;
	}
	 
	public void processMessage(long now, int moduleFlag)
	{ 
		ArrayList<Player> allPlayer = null;
		
		synchronized(playerMap)
		{
			Collection<Player> playerSet = playerMap.values(); 
			allPlayer = new ArrayList<Player>(playerSet.size());
			
			Iterator<Player> iterator = playerSet.iterator(); 
			while (iterator.hasNext())
			{
				Player player = iterator.next();
				allPlayer.add(player); 
			}
		}
		
		Iterator<Player> iterator = allPlayer.iterator();
		while (iterator.hasNext())
		{
			Player player = iterator.next(); 
			player.processMessage(now, moduleFlag); 
		}
	}
	
	private static Integer playerRuntimeID = 0;
	private HashMap<Integer, Player> playerMap;
}
